﻿using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using Microsoft.Practices.Unity;
using MiniStock.Entities.Common;
using System.ComponentModel.DataAnnotations;

namespace MiniStock.Entities.Stock
{
    [DataContract(IsReference = true)]
    public class Customer : EntityBase
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public Address HQAddress { get; set; }
        [DataMember]
        public Address ShippingAddress { get; set; }
        [DataMember]
        public ContactPerson ContactPerson { get; set; }
        [DataMember]
        public List<Order> Orders { get; set; }

        public Customer()
        {
            HQAddress = new Address();
            ShippingAddress = new Address();
            ContactPerson = new ContactPerson();
            Orders = new List<Order>();
        }

        public override void CopyFrom(EntityBase source, int depthLimit = -1)
        {
            var customer = (Customer) source;

            base.CopyFrom(source, -1);
            this.Name = customer.Name;
            this.HQAddress = (Address) customer.HQAddress.Clone();
            this.ShippingAddress = (Address) customer.ShippingAddress.Clone();
            this.ContactPerson = (ContactPerson) customer.ContactPerson.Clone();

            if (depthLimit != 0)
            {
                this.Orders = customer.Orders.Select(i =>
                                                         {
                                                             var j = new Order();
                                                             j.CopyFrom(i, depthLimit - 1);
                                                             return j;
                                                         }).ToList();
            }
        }


        #region Validators

        public static class Validator
        {
            public static void CustomerNameMandatory(Customer current, IEntityProvider provider, string newName)
            {
                if (string.IsNullOrEmpty(newName))
                    throw new ValidationException("Customer name must be specified");
            }

            public static void CustomerNameUnique(Customer current, IEntityProvider provider, string newName)
            {
                if (provider.All<Customer>().Exists(i => i.Name == newName && (current == null || i.Id != current.Id)))
                {
                    throw new ValidationException("Customer name must be unique");
                }
            }
        }

        #endregion
    }
}
